package com.hjx.img;

import org.apache.commons.io.FileUtils;

import javax.imageio.ImageIO;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;
import java.util.List;

/**
 * Created by liwj
 * date:2018/2/23
 * comment:
 */
public class ImageSplit {

    public static final String desktop = "C:\\Users\\woshi\\Desktop\\";
    /**
     * 切割图片
     *
     * @throws Exception
     */
    private static void splitImage() throws Exception {
        Map<String, Integer> base64IndexMappings = new LinkedHashMap<>();
        String originalImg = desktop + "error1.jpg";
        File file = new File(originalImg);
        FileInputStream fis = new FileInputStream(file);
        BufferedImage image = ImageIO.read(fis);

        int rows = 2;
        int cols = 95;
        int chunks = rows * cols;

        int chunkWidth = image.getWidth() / cols;
        int chunkHeight = image.getHeight() / rows;

        int count = 0;
        BufferedImage[] imgs = new BufferedImage[chunks];
        for (int x = 0; x < rows; x++) {
            for (int y = 0; y < cols; y++) {
                imgs[count] = new BufferedImage(chunkWidth, chunkHeight, image.getType());

                Graphics2D gr = imgs[count++].createGraphics();
                gr.drawImage(image, 0, 0, chunkWidth, chunkHeight,
                        chunkWidth * y, chunkHeight * x,
                        chunkWidth * y + chunkWidth, chunkHeight * x + chunkHeight, null);
                gr.dispose();
            }
        }
        for (int i = 0; i < imgs.length / 2; i++) {
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            ImageIO.write(imgs[i], "jpg", outputStream);
            System.out.println(Base64.getEncoder().encodeToString(outputStream.toByteArray()) + ":" + i);
            base64IndexMappings.put(Base64.getEncoder().encodeToString(outputStream.toByteArray()), i);
            ImageIO.write(imgs[i], "jpg", new File(desktop + "splitImage\\" + i + ".jpg"));
        }

    }

    private static Map<String, Integer> splitImage(String imgPath) throws Exception {
        Map<String, Integer> base64IndexMappings = new HashMap<>();
        BufferedImage image = ImageIO.read(new FileInputStream(new File(imgPath)));

        int rows = 2;
        int cols = 95;
        int chunks = rows * cols;

        int chunkWidth = image.getWidth() / cols;
        int chunkHeight = image.getHeight() / rows;

        int count = 0;
        BufferedImage[] imgs = new BufferedImage[chunks];
        for (int x = 0; x < rows; x++) {
            for (int y = 0; y < cols; y++) {
                imgs[count] = new BufferedImage(chunkWidth, chunkHeight, image.getType());

                Graphics2D gr = imgs[count++].createGraphics();
                gr.drawImage(image, 0, 0, chunkWidth, chunkHeight,
                        chunkWidth * y, chunkHeight * x,
                        chunkWidth * y + chunkWidth, chunkHeight * x + chunkHeight, null);
                gr.dispose();
            }
        }
        for (int i = 0; i < imgs.length / 2; i++) {
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            ImageIO.write(imgs[i], "jpg", outputStream);
//            System.out.println(Base64.getEncoder().encodeToString(outputStream.toByteArray()));
            base64IndexMappings.put(Base64.getEncoder().encodeToString(outputStream.toByteArray()), i);
        }
        return base64IndexMappings;

    }

    /**
     * 合并图片
     *
     * @throws Exception
     */
    private static void mergeImage() throws Exception {
//        int rows = 1;
//        int[] asciis = {0,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126};
//        int cols = asciis.length;
        int rows = 2;
        int cols = 95;
        int chunks = rows * cols;

        int chunkWidth, chunkHeight;
        int type;

        File[] imgFiles = new File[chunks];
        for (int i = 0; i < chunks; i++) {
//            imgFiles[i] = new File(desktop + "splitImage\\" + asciis[i] + ".jpg");
            imgFiles[i] = new File(desktop + "splitImage\\" + i + ".jpg");
        }

        BufferedImage[] buffImages = new BufferedImage[chunks];
        for (int i = 0; i < chunks; i++) {
            buffImages[i] = ImageIO.read(imgFiles[i]);
        }
        type = buffImages[0].getType();
        chunkWidth = buffImages[0].getWidth();
        chunkHeight = buffImages[0].getHeight();

        BufferedImage finalImg = new BufferedImage(chunkWidth * cols, chunkHeight * rows, type);

        int num = 0;
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                finalImg.createGraphics().drawImage(buffImages[num], chunkWidth * j, chunkHeight * i, null);
                num++;
            }
        }

        ImageIO.write(finalImg, "jpeg", new File(desktop + "splitImage\\merge.jpg"));
    }

    public static void main(String[] args) {
        try {
            splitImage();
//            mergeImage();
        } catch (Exception e) {
            e.printStackTrace();
        }
//        base64();

//        Arrays.stream(stringToAscii("574311651")).forEach(System.out::println);
//
//        System.out.println(asciiToString("53,55,52,51,49,49,54,53,49"));
    }

    public static String asciiToString(String value) {
        StringBuffer sbu = new StringBuffer();
        String[] chars = value.split(",");
        for (int i = 0; i < chars.length; i++) {
            sbu.append((char) Integer.parseInt(chars[i]));
        }
        return sbu.toString();
    }

    public static String[] stringToAscii(String value) {
        String[] chars = value.split("|");
        String[] asciis = new String[chars.length];
        for (int i = 0; i < chars.length; i++) {
            asciis[i] = String.valueOf((int)chars[i].charAt(0));
        }
        return asciis;
    }


    public static void base64(){
        String passwordIndexs = "123456978";
        List<String> pass =Arrays.asList(passwordIndexs.split("|"));

        Map<String, String> base64Mappings = new HashMap<String, String>();
        Arrays.stream(new File(desktop + "tokens").listFiles()).forEach(file -> {
            try {
//                String imgToBase64 = file.getName() + ":" + Base64.getEncoder().encodeToString(FileUtils.readFileToByteArray(file));
//                System.out.println(imgToBase64);
                base64Mappings.put(Base64.getEncoder().encodeToString(FileUtils.readFileToByteArray(file)), file.getName().replaceAll(".jpg", ""));
            } catch (IOException e) {
                e.printStackTrace();
            }
        });

        base64Mappings.forEach((k,v) -> {
//            System.out.println("\"" + asciiToString(v) + "\" : \"" + k + "\",");
            System.out.println("\"" + v + "\" : \"" + k + "\",");
        });
//        Arrays.stream(new File(desktop + "splitImage").listFiles()).filter(file -> {
//
//            return pass.contains(file.getName().replaceAll(".jpg", ""));
//        }).forEach(file -> {
//            try {
////                String imgToBase64 = file.getName() + ":" + Base64.getEncoder().encodeToString(FileUtils.readFileToByteArray(file));
////                System.out.println(imgToBase64);
//                String password = base64Mappings.get(Base64.getEncoder().encodeToString(FileUtils.readFileToByteArray(file)));
//                System.out.println(asciiToString(password));
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        });
//
    }
}